<?php

/*
 +-----------------------------------------------------------------------+
 | plugins/sauserprefs/save_sauserprefs.inc                              |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Save user spamassassin settings to sql                              |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Philip Weir                                                   |
 +-----------------------------------------------------------------------+
 | Requires: plugins/sauserprefs/config.inc.php                          |
 +-----------------------------------------------------------------------+

 $Id: $

*/

require_once('plugins/sauserprefs/config.inc.php');

$user_db = new rcube_mdb2($sauserprefs_config['db_dsnw'], $sauserprefs_config['db_dsnr'], $sauserprefs_config['db_persistent']);
$user_db->db_connect('w');

// check DB connections and exit on failure
if ($err_str = $user_db->is_error()) {
  raise_error(array(
    'code' => 603,
    'type' => 'db',
    'message' => $err_str), FALSE, TRUE);
}

// global settings
$global_prefs = array();

$sql_result = $user_db->query(
  "SELECT ". $sauserprefs_config['sql_preference_field'] .", ". $sauserprefs_config['sql_value_field'] ."
   FROM   ". $sauserprefs_config['sql_table_name'] ."
   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '\$GLOBAL'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_from'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'blacklist_from'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_to';"
  );

while ($sql_result && ($sql_arr = $user_db->fetch_assoc($sql_result)))
	$global_prefs[$sql_arr[$sauserprefs_config['sql_preference_field']]] = $sql_arr[$sauserprefs_config['sql_value_field']];

$global_prefs = array_merge($sauserprefs_config['default_prefs'], $global_prefs);

// user settings
$user_prefs = array();

$sql_result = $user_db->query(
  "SELECT ". $sauserprefs_config['sql_preference_field'] .", ". $sauserprefs_config['sql_value_field'] ."
   FROM   ". $sauserprefs_config['sql_table_name'] ."
   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_from'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'blacklist_from'
   AND    ". $sauserprefs_config['sql_preference_field'] ." <> 'whitelist_to';"
  );

while ($sql_result && ($sql_arr = $user_db->fetch_assoc($sql_result)))
	$user_prefs[$sql_arr[$sauserprefs_config['sql_preference_field']]] = $sql_arr[$sauserprefs_config['sql_value_field']];

$new_prefs = array();

if ($sauserprefs_config['general_settings']['score'])
	$new_prefs['required_hits'] = $_POST['_spamthres'];

if ($sauserprefs_config['general_settings']['subject'])
	$new_prefs['rewrite_header Subject'] = $_POST['_spamsubject'];

if ($sauserprefs_config['general_settings']['language']) {
	$new_prefs['ok_locales'] = implode(" ", $_POST['_spamlang']);
	$new_prefs['ok_languages'] = $new_prefs['ok_locales'];
}

if ($_POST['_do_headers'] == '1') {
	$new_prefs['fold_headers'] = empty($_POST['_spamfoldheaders']) ? "0" : $_POST['_spamfoldheaders'];
	$spamchar = empty($_POST['_spamlevelchar']) ? "*" : $_POST['_spamlevelchar'];
	if ($_POST['_spamlevelstars'] == "1") {
		$new_prefs['add_header all Level'] = "_STARS(". $spamchar .")_";
		$new_prefs['remove_header all'] = "0";
	}
	else {
		$new_prefs['add_header all Level'] = "";
		$new_prefs['remove_header all'] = "Level";
	}
}

if ($_POST['_do_tests'] == '1') {
	$new_prefs['use_razor1'] = empty($_POST['_spamuserazor1']) ? "0" : $_POST['_spamuserazor1'];
	$new_prefs['use_razor2'] = empty($_POST['_spamuserazor2']) ? "0" : $_POST['_spamuserazor2'];
	$new_prefs['use_pyzor'] = empty($_POST['_spamusepyzor']) ? "0" : $_POST['_spamusepyzor'];
	$new_prefs['use_bayes'] = empty($_POST['_spamusebayes']) ? "0" : $_POST['_spamusebayes'];
	$new_prefs['use_dcc'] = empty($_POST['_spamusedcc']) ? "0" : $_POST['_spamusedcc'];

	if ($_POST['_spamskiprblchecks'] == "1")
		$new_prefs['skip_rbl_checks'] = "";
	else
		$new_prefs['skip_rbl_checks'] = "1";
}

if ($_POST['_do_report'] == '1')
	$new_prefs['report_safe'] = $_POST['_spamreport'];

foreach ($new_prefs as $preference => $value){
	if ($value == "" || $value == $global_prefs[$preference]) {
		$result = false;

		$user_db->query(
		  "DELETE FROM ". $sauserprefs_config['sql_table_name'] ."
		   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
		   AND    ". $sauserprefs_config['sql_preference_field'] ." = '". $preference ."';"
		  );

		$result = $user_db->affected_rows();

		if (!$result)
			break;
	}
	elseif (array_key_exists($preference, $user_prefs) && $value != $user_prefs[$preference]) {
		$result = false;

		$user_db->query(
		  "UPDATE ". $sauserprefs_config['sql_table_name'] ."
		   SET    ". $sauserprefs_config['sql_value_field'] ." = '". $value ."'
		   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
		   AND    ". $sauserprefs_config['sql_preference_field'] ." = '". $preference ."';"
		  );

		$result = $user_db->affected_rows();

		if (!$result)
			break;
	}
	elseif ($value != $global_prefs[$preference] && $value != $user_prefs[$preference]) {
		$result = false;

		$user_db->query(
		  "INSERT INTO ". $sauserprefs_config['sql_table_name'] ."
		   (".$sauserprefs_config['sql_username_field'].", ".$sauserprefs_config['sql_preference_field'].", ".$sauserprefs_config['sql_value_field'].")
		   VALUES ('". $_SESSION['username'] ."', '". $preference ."', '". $value ."')"
		  );

		$result = $user_db->affected_rows();

		if (!$result)
			break;
	}
}

if ($result) {
	if ($_POST['_do_addresses'] == '1') {
		$acts = $_POST['_address_rule_act'];
		$prefs = $_POST['_address_rule_field'];
		$vals = $_POST['_address_rule_value'];

		foreach ($acts as $idx => $act){
			if ($act == "DELETE") {
				$result = false;

				$user_db->query(
				  "DELETE FROM ". $sauserprefs_config['sql_table_name'] ."
				   WHERE  ". $sauserprefs_config['sql_username_field'] ." = '". $_SESSION['username'] ."'
				   AND    ". $sauserprefs_config['sql_preference_field'] ." = '". $prefs[$idx] ."'
				   AND    ". $sauserprefs_config['sql_value_field'] ." = '". $vals[$idx] . "';"
				  );

				$result = $user_db->affected_rows();

				if (!$result)
					break;
			}
			elseif ($act == "INSERT") {
				$result = false;

				$user_db->query(
				  "INSERT INTO ". $sauserprefs_config['sql_table_name'] ."
				   (".$sauserprefs_config['sql_username_field'].", ".$sauserprefs_config['sql_preference_field'].", ".$sauserprefs_config['sql_value_field'].")
				   VALUES ('". $_SESSION['username']. "', '". $prefs[$idx] . "', '". $vals[$idx] ."')"
				  );

				$result = $user_db->affected_rows();

				if (!$result)
					break;
			}
		}
	}

	if ($result)
		$OUTPUT->show_message('sauserprefchanged', 'confirmation');
	else
		$OUTPUT->show_message('sauserpreffailed', 'error');
}
else {
	$OUTPUT->show_message('sauserpreffailed', 'error');
}

// go to next step
rcmail_overwrite_action('sauserprefs');

?>